import React, { useEffect, useState, useRef } from 'react'
import DocumentTitle from 'react-document-title'
import { useHistory } from 'react-router-dom'
import { KeepAlive, useActivate, useUnactivate } from 'react-activation'
import { getHomeGoodsList, getBanner, getNotices } from '@api/home'
import axios from 'axios'
import { mixRoute } from '@/utils'


import BetterScroll from 'components/betterScroll'
import { HomeGoodsItemHOC } from '@common/goodsItem'
import { Banner, MinGoodsDetail, HomeNotice, Search } from './component/home'
import { LoadingMore } from 'components/loading'
import { Toast, WingBlank } from 'antd-mobile'
import { HomeStyle } from './style'


let config = {
    page: 0,
    page_num: 5,
}

const Home = () => {

    const home_bs_ref = useRef()
    const [homeGoodsList, setHomeGoodsList] = useState([])
    const [homeOtherData, setHomeOtherData] = useState({})
    const [isLoadMore, setIsLoadMore] = useState(true)

    useActivate(() => {

        console.log('TestFunction: 缓存恢复', config.page)

        let storegePage = parseInt(config.page)
        const pageNum = storegePage === 0 ? 5 : storegePage * 5

        axios.all([getNotices(), getBanner(), getHomeGoodsList({ action: 'get_index_goods', page: 0, page_num: pageNum })]).then(axios.spread((res1, res2, res3) => {
            setHomeOtherData({
                time: 3000,
                notices: res1,
                banner: res2.banner
            })
            setHomeGoodsList(res3.index)
        }))
    })

    useUnactivate(() => {
        console.log('TestFunction: 缓存')
    })


    useEffect(() => {
        axios.all([getNotices(), getBanner(), getHomeGoodsList(config)]).then(axios.spread((res1, res2, res3) => {
            console.log(res1, res2, res3)
            setHomeOtherData({
                time: 3000,
                notices: res1,
                banner: res2.banner
            })
            setHomeGoodsList(res3.index)
        }))

    }, [])


    useEffect(() => {
        try {
            home_bs_ref.current.BScroll.refresh()
            home_bs_ref.current.BScroll.finishPullUp();
            console.log(home_bs_ref.current.BScroll)
        } catch (error) {

        }

    }, [homeGoodsList])



    return (
        <HomeStyle>
            <div className='home-container'>
                <div className='home-box'>
                    <Search getSerachData={e => { getSerachData(e) }} />
                    <BetterScroll
                        isLoadMore={isLoadMore}
                        loadMore={() => { getLoadMoreGoods() }}
                        ref={home_bs_ref}
                        className='home-bs-style'
                        style={{
                            height: " calc( calc( 100vh - 2.46rem - 0px) - env(safe-area-inset-bottom) )  ",
                            bottom: '1.3rem',
                            top: '0'
                        }} >

                        {homeOtherData?.banner?.length > 0 && <Banner data={homeOtherData.banner} time={homeOtherData.time}></Banner>}

                        {homeOtherData?.notices?.length > 0 && <HomeNotice notices={homeOtherData.notices} />}

                        {
                            homeGoodsList?.map((item, key) => {
                                return (
                                    <HomeGoodsItemHOC MinGoodsDetail={MinGoodsDetail} key={key + item.gimg} {...item} marginStyle={{ margin: ".16rem 0", boxSizing: 'border-box', padding: '.32rem 0' }} />
                                )
                            })
                        }

                        {

                            <LoadingMore path='home' length={homeGoodsList?.length} number={3} isLoading={isLoadMore} />
                        }
                    </BetterScroll>
                </div>
            </div>
        </HomeStyle>

    )

    async function getGoodsList() {


        console.log('函数执行', config.page)

        config.page += 1

        let res = await getHomeGoodsList(config);

        let newList
        newList = res.index
        console.log(newList)

        if (res.index.length !== 0) {
            setHomeGoodsList([...homeGoodsList, ...newList])
            home_bs_ref.current.BScroll.finishPullUp();

        } else {
            console.log('加载完了')
            setIsLoadMore(false)
        }

        try {



        } catch (error) {

        }


    }

    async function getSerachData(key) {
        let config = {
            action: 'get_index_goods',
            page: 0,
            page_num: 20,
            name: key
        }

        let res = await getHomeGoodsList(config)

        if (res.index.length > 0) {

            setHomeGoodsList(res.index)

        } else {
            Toast.info('未搜到相关商品', 1)
        }
    }

    function getLoadMoreGoods() {

        if (isLoadMore) {
            getGoodsList()
        }
    }
}

const KeepHome = () => {
    const history = useHistory()
    const shareParams = JSON.parse(window.localStorage.getItem('shareParams'))
    console.log(shareParams)

    useEffect(() => {
        if (shareParams) {
            const { goodsid, groupid } = shareParams
            if (goodsid) {
                mixRoute(history, `/goodsdetail/${goodsid}`)
            }
            if (groupid) {
                mixRoute(history, `/group/${groupid}`)
            }
        }
    }, [])

    return (
        <>
            <DocumentTitle title={'火蝶甄品'} />
            <KeepAlive name="home" when={() => { return true }} saveScrollPosition="screen" >
                <WingBlank size="md">
                    <Home />
                </WingBlank>
            </KeepAlive>
            {/* <NoticeBar /> */}
        </>
    )


}



export default KeepHome;